package com.hsoft.zhxy.common.util;

import java.io.IOException;
import java.text.MessageFormat;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.log4j.Log4j2;

/**
 * Copyright © 2017 哈尔滨工业大学软件工程股份有限公司. All rights reserved.
 * 
 * @Title: HttpClientUtil.java
 * @Description: 基于HttpClient封装的工具类
 * @Prject: demoWeb
 * @Package: com.hsoft.mss.common.util
 * @author: mlingwei
 * @date: 2017年2月13日 下午4:24:52
 */
@Log4j2
public class HttpClientUtils {

    private static final String UTF_8 = "UTF-8";

    /**
     * Httpclient POST请求
     * @param url 请求地址
     * @param params 请求参数
     * @return
     * @throws IOException
     */
    public static String post(String url, String params) {
        
        // 创建httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 设置连接超时时间等配置项
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .build();

        String body = "";
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setConfig(requestConfig);
        
        // 传入参数
        httpPost.setEntity(new StringEntity(params, UTF_8));
        CloseableHttpResponse response = null;
        try {
            // 执行请求并获取响应
            response = httpclient.execute(httpPost);
            
            // 获取响应码，如果响应码为200，则获取响应数据
            int statuCode = response.getStatusLine().getStatusCode();
            if (statuCode == 200) {
                HttpEntity entity = response.getEntity();
                body = EntityUtils.toString(entity, UTF_8);
                EntityUtils.consume(entity);
            }else {
                String msg = MessageFormat.format("httpclient请求的目标服务器返回错误，请求地址为： {0}，请求码为：{1}，返回内容：{2}", url, statuCode, response.getStatusLine().getReasonPhrase());
                log.info(msg);
            }
            
        } catch(IOException e) {
            String msg = MessageFormat.format("httpclient请求的连接协议或地址发生错误，请求地址为： {0}", url);
            log.error(msg, e);
        } finally {
            if(response != null) {
                try {
                    response.close();
                    httpclient.close();
                } catch (IOException e) {
                    String msg = MessageFormat.format("httpclient关闭连接时发生错误，请求地址为： {0}", url);
                    log.error(msg, e);
                }
            }
        }
        return body;
    }


    /**
     * Httpclient GET请求
     * @param url
     * @return 
     * @throws IOException
     */
    public static String get(String url) {

        // 创建httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 设置连接超时时间等配置项
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .build();

        String body = "";
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        httpGet.setHeader("Content-type", "application/json");
        
        CloseableHttpResponse response = null;
        try {
            // 执行请求并获取响应
            response = httpclient.execute(httpGet);
            
            // 获取响应码，如果响应码为200，则获取响应数据
            int statuCode = response.getStatusLine().getStatusCode();
            if (statuCode == 200) {
                HttpEntity entity = response.getEntity();
                body = EntityUtils.toString(entity, UTF_8);
                EntityUtils.consume(entity);
            }else {
                String msg = MessageFormat.format("httpclient请求的目标服务器返回错误，请求地址为： {0}，请求码为：{1}，返回内容：{2}", url, statuCode, response.getStatusLine().getReasonPhrase());
                log.info(msg);
            }
            
        } catch(IOException e) {
            String msg = MessageFormat.format("httpclient请求的连接协议或地址发生错误，请求地址为： {0}", url);
            log.error(msg, e);
        } finally {
            if(response != null) {
                try {
                    response.close();
                    httpclient.close();
                } catch (IOException e) {
                    String msg = MessageFormat.format("httpclient关闭连接时发生错误，请求地址为： {0}", url);
                    log.error(msg, e);
                }
            }
        }
        return body;
    }

    public static void main(String[] args){

        String rs11 = HttpClientUtils.get("http://127.0.0.1:8080/dbtest/dbtest/getDbtest11?user=孟令伟&pass=mlw&age=123456789");
        log.info("11==>> " + rs11);
        
        String rs12 = HttpClientUtils.get("http://127.0.0.1:8080/dbtest/dbtest/getDbtest12/孟令伟/mlw/123456789");
        log.info("12==>> " + rs12);
        
        String rs13 = HttpClientUtils.get("http://127.0.0.1:8080/dbtest/dbtest/getDbtest13?user=%E5%AD%9F%E4%BB%A4%E4%BC%9F&pass=mlw&age=123456789");
        log.info("13==>> " + rs13);

        JSONObject json = new JSONObject();
        json.put("user", "mlw");
        json.put("pass", "孟令伟");
        json.put("age", 123456789);
        String rs21 = HttpClientUtils.post("http://127.0.0.1:8080/dbtest/dbtest/getDbtest21", json.toString());
        log.info("21==>> " + rs21);

    }

}